<template>
  <div class="asset-selector">
    <!-- 搜索条件 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="资产编号" prop="assetNo">
        <el-input
          v-model="queryParams.assetNo"
          placeholder="请输入资产编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资产名称" prop="assetName">
        <el-input
          v-model="queryParams.assetName"
          placeholder="请输入资产名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 状态说明 -->
    <div style="margin-bottom: 10px; padding: 8px 12px; background-color: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px; font-size: 12px; color: #409eff;">
      <i class="el-icon-info"></i>
      <span style="margin-left: 4px;">
        报修状态说明：<span style="color: #67c23a;">可报修</span> - 可以添加报修；<span style="color: #e6a23c;">待报修</span> - 已有未完成报修，不可重复选择
      </span>
    </div>

    <!-- 资产列表 -->
    <el-table
      v-loading="loading"
      :data="assetList"
      height="300"
      ref="multipleTable"
      :highlight-current-row="!multiple"
      @row-click="multiple ? null : onRowClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="!multiple" label="选择" width="55" align="center" class-name="select-col">
        <template slot-scope="scope">
          <el-radio :label="scope.row.assetNo" v-model="selectedAssetNo" :disabled="!canRepair(scope.row)"><span class="hidden-label">{{ scope.row.assetNo }}</span></el-radio>
        </template>
      </el-table-column>
      <el-table-column
        v-else
        type="selection"
        width="55"
        align="center"
        :selectable="checkSelectable"
      />
      <el-table-column label="资产编号" align="center" prop="assetNo" width="120" />
      <el-table-column label="资产名称" align="center" prop="assetName" min-width="150" />
      <el-table-column label="设备状态" align="center" prop="statusCode" width="100">
        <template slot-scope="scope">
          <el-tag :type="getStatusType(scope.row.statusCode)">
            {{ getStatusName(scope.row.statusCode) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="报修状态" align="center" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.hasUnfinishedReport" type="warning" size="mini">待报修</el-tag>
          <el-tag v-else-if="!canRepair(scope.row)" type="info" size="mini">不可报修</el-tag>
          <el-tag v-else type="success" size="mini">可报修</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 操作按钮 -->
    <div slot="footer" class="dialog-footer" style="text-align: right; margin-top: 20px;">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
// 导入资产API
import { listAssetDTO } from '@/api/asset/asset'

export default {
  name: 'AssetSelector',
  props: {
    selectedAssets: {
      type: Array,
      default: () => []
    },
    multiple: {
      type: Boolean,
      default: true
    },
    // 是否仅显示非正常资产（报修场景用）
    onlyAbnormal: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      assetList: [],
      total: 0,
      multipleSelection: [],
      selectedAssetNo: null,
      pendingAssetNos: [], // 已有未完成报修的资产编号
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetNo: null,
        assetName: null
      }
    }
  },
  async created() {
    await this.loadPendingAssetNos()
    this.getList()
  },
  mounted() {
    // 设置已选择的资产为选中状态
    this.$nextTick(() => {
      this.setSelectedAssets()
    })
  },
  methods: {
    /** 是否允许报修：设备非正常 且 无未完成报修 */
    canRepair(row) {
      if (!row) return false
      if (row.hasUnfinishedReport) return false
      const normalCodes = ['ASSET_STATUS_001', 'NORMAL', 'NORMAL_001']
      return !normalCodes.includes(String(row.statusCode || ''))
    },
    /** 查询资产列表 */
    getList() {
      this.loading = true
      listAssetDTO(this.queryParams).then(response => {
      const rows = response.data || []
      // 可选：仅显示"故障"状态的设备（仅显示 ASSET_STATUS_002）
      let filteredRows = this.onlyAbnormal
        ? rows.filter(a => a && a.statusCode === 'ASSET_STATUS_002')
        : rows
      
      // 为每个资产添加待报修状态标记
      this.assetList = filteredRows.map(asset => ({
        ...asset,
        hasUnfinishedReport: this.pendingAssetNos.includes(asset.assetNo)
      }))
      
      this.total = this.assetList.length
      this.loading = false
      // 数据加载完成后设置已选择的资产
      this.$nextTick(() => {
        this.setSelectedAssets()
      })
      }).catch(() => {
        this.loading = false
      })
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        assetNo: null,
        assetName: null
      }
      this.handleQuery()
    },
    
    /** 多选变化事件（仅在 multiple=true 时触发） */
    handleSelectionChange(selection) {
      if (!this.multiple) return
      this.multipleSelection = selection
    },
    
    /** 行点击时切换单选 */
    onRowClick(row) {
      // 不可报修（正常/已存在未完成报修）时不选中
      if (!this.canRepair(row)) return
      this.selectedAssetNo = row && row.assetNo
    },
    
    
    /** 获取状态名称 */
    getStatusName(statusCode) {
      const statusMap = {
        'ASSET_STATUS_001': '正常',
        'ASSET_STATUS_002': '故障',
        'ASSET_STATUS_003': '闲置',
        'ASSET_STATUS_004': '报废'
      }
      return statusMap[statusCode] || statusCode
    },
    
    /** 获取状态标签类型 */
    getStatusType(statusCode) {
      const typeMap = {
        'ASSET_STATUS_001': 'success',  // 正常 - 绿色
        'ASSET_STATUS_002': 'danger',   // 故障 - 红色
        'ASSET_STATUS_003': 'info',     // 闲置 - 蓝色
        'ASSET_STATUS_004': 'info'      // 报废 - 灰色
      }
      return typeMap[statusCode] || 'info'
    },
    
    /** 检查行是否可选择 */
    checkSelectable(row) {
      // 已有未完成报修的资产不可选择
      return !row.hasUnfinishedReport
    },
    
    /** 加载已有未完成报修的资产编号 */
    loadPendingAssetNos() {
      return new Promise((resolve) => {
        // 使用现有的报修列表API来获取未完成的报修
        import('@/api/repair/order').then(api => {
          // 获取所有报修单，然后筛选出未完成的
          api.listOrders({ pageNum: 1, pageSize: 9999 }).then(response => {
            if (response.rows && Array.isArray(response.rows)) {
              // 已完成的状态：草稿、已承认、已关闭、已完成、已取消、已拒绝
              const completedStatuses = ['DRAFT', 'ACKNOWLEDGED', 'CLOSED', 'DONE', 'CANCELLED', 'REJECTED']
              
              // 筛选出未完成的报修单（状态不在已完成列表中）
              const unfinishedReports = response.rows.filter(report => 
                report.status && !completedStatuses.includes(report.status)
              )
              
              // 提取资产编号
              this.pendingAssetNos = unfinishedReports
                .map(report => report.assetNo)
                .filter(assetNo => assetNo) // 过滤掉空值
            } else {
              this.pendingAssetNos = []
            }
            resolve()
          }).catch(error => {
            console.error('获取报修列表失败:', error)
            // 如果获取失败，设置为空数组，不影响正常选择
            this.pendingAssetNos = []
            resolve()
          })
        }).catch(error => {
          console.error('导入API失败:', error)
          this.pendingAssetNos = []
          resolve()
        })
      })
    },
    
    
    /** 确认选择 */
    handleConfirm() {
      if (this.multiple) {
        if (this.multipleSelection.length === 0) {
          this.$message.warning('请至少选择一个资产')
          return
        }
        const newAssets = []
        const duplicateAssets = []
        this.multipleSelection.forEach(asset => {
          const exists = this.selectedAssets.some(selectedAsset => selectedAsset.assetNo === asset.assetNo)
          if (exists) {
            duplicateAssets.push(asset.assetName)
          } else {
            newAssets.push(asset)
          }
        })
        if (duplicateAssets.length > 0) {
          this.$message.warning(`以下资产已经选择过了：${duplicateAssets.join('、')}`)
        }
        if (newAssets.length > 0) {
          this.$emit('confirm', [...this.selectedAssets, ...newAssets])
          this.$emit('close')
        } else if (duplicateAssets.length > 0) {
          this.$message.info('没有新的资产需要添加')
        }
      } else {
        if (!this.selectedAssetNo) {
          this.$message.warning('请选择一个资产')
          return
        }
        const selected = this.assetList.find(a => a.assetNo === this.selectedAssetNo)
        if (selected) {
          this.$emit('confirm', [selected])
          this.$emit('close')
        }
      }
    },
    
    /** 取消选择 */
    handleCancel() {
      this.$emit('close')
      this.$emit('cancel')
    },
    
    /** 设置已选择的资产为选中状态 */
    setSelectedAssets() {
      if (this.multiple) {
        if (this.selectedAssets && this.selectedAssets.length > 0) {
          this.$nextTick(() => {
            this.assetList.forEach(asset => {
              const isSelected = this.selectedAssets.some(selectedAsset => selectedAsset.assetNo === asset.assetNo)
              if (isSelected) {
                this.$refs.multipleTable && this.$refs.multipleTable.toggleRowSelection(asset, true)
              }
            })
          })
        }
      } else {
        if (this.selectedAssets && this.selectedAssets.length > 0) {
          const first = this.selectedAssets[0]
          this.selectedAssetNo = first && first.assetNo
        }
      }
    }
  }
}
</script>

<style scoped>
.asset-selector {
  padding: 20px;
}
</style>
